package com.neo.shiro.filters;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import com.alibaba.fastjson.JSONObject;

public class MyPermissionsAuthorizationFilter extends PermissionsAuthorizationFilter{
	
	private static Logger logger = LoggerFactory.getLogger(MyPermissionsAuthorizationFilter.class);
	
	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
		
		logger.info("==>[当前用户没有权限]");
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        String requestedWith = httpServletRequest.getHeader("X-Requested-With");
        if (!StringUtils.isEmpty(requestedWith) && "XMLHttpRequest".equalsIgnoreCase(requestedWith)) {//如果是ajax返回指定格式数据
        	Map<String,String> resultMap = new HashMap<String, String>();
			logger.info("==>[当前用户没有权限，并且是Ajax请求！]");
			resultMap.put("code", "400");
			resultMap.put("message", "\u5F53\u524D\u7528\u6237\u6CA1\u6709\u767B\u5F55\uFF01");
        	httpServletResponse.setCharacterEncoding("UTF-8");
            httpServletResponse.setContentType("application/json; charset=utf-8");
            httpServletResponse.setHeader("401", "当前用户没有权限，并且是Ajax请求！");
            PrintWriter out = httpServletResponse.getWriter();
            out.write(JSONObject.toJSONString(resultMap));
        } else {//如果是普通请求进行重定向
            httpServletResponse.sendRedirect("/403");
        }
		return false;
	}
	
	@Override
	public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException {
		logger.info("==>isAccessAllowed()");
		return super.isAccessAllowed(request, response, mappedValue);
	}
}
